package cc.rengu.redp.flowable.bizmodel;

import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.flowable.bizmodel.divide.Divider;
import cc.rengu.redp.flowable.bizmodel.metadata.ModelHandler;
import cc.rengu.redp.flowable.bizmodel.db.domain.BizCfgModel;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class BizModelNormalBuilder implements BizModelBuilder {

    public final static String RESERVE_FIELD_KEY = "key";

    @Autowired
    private Divider divider;
    @Autowired
    private ModelHandler modelService;

    @Override
    public void trigToBuild(String flowJsonData, String procDefId, String nodeId) {
        JSONObject flowDataJsonObj = JSONObject.parseObject(flowJsonData);
        if (flowDataJsonObj.isEmpty()) return;
        try {
            checkJsonData(flowDataJsonObj);
        } catch (RedpException e) {
            log.error("checkJsonData failed", e);
            return;
        }
        List<BizCfgModel> relatedModels = divider.divideToModels(procDefId, nodeId);
        for (BizCfgModel bizCfgModel : relatedModels) {
          this.runBuild(flowDataJsonObj, bizCfgModel);
        }
    }

    @Override
    public void checkJsonData(JSONObject jsonDataObj) throws RedpException {
        if (jsonDataObj != null && jsonDataObj.get(RESERVE_FIELD_KEY) != null){
            throw new RedpException("流程数据中不可有保留关键字: " + RESERVE_FIELD_KEY);
        }
    }

    @Async
    public void runBuild(JSONObject jsonObj, BizCfgModel bizCfgModel) {
        modelService.create(jsonObj, bizCfgModel);
    }
}
